﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Data.SqlClient;

namespace WorkFlowSystem.Common
{
    class Logger
    {
        public static void SetLogPath()
        {
            string log_dir = "";
            ConfigOperator cfg = new ConfigOperator();
            if (cfg.GetStrValue("appSettings", "log_dir", ref log_dir) < 0)
            {
                log_dir = Application.StartupPath + @"\Logs";
            }
            if (!Directory.Exists(log_dir))
            {
                Directory.CreateDirectory(log_dir);
            }
            m_path = log_dir + @"\trace.log";
        }

        public static int WriteSqlConsole(string sql, List<SqlParameter> para_list)
        {
            if (para_list == null || para_list.Count == 0)
            {
                Console.WriteLine(sql);
                return 0;
            }

            for (int i = 0; i < para_list.Count; i++)
            {
                sql = sql.Replace(para_list[i].ParameterName, para_list[i].Value.ToString());
            }
            Console.WriteLine(sql);
            return 0;
        }

        public static int WriteConsole(string logstr)
        {
            Console.WriteLine(logstr);
            return 0;
        }

        public static int WriteSqlLog(string sql, List<SqlParameter> para_list)
        {
            if (before_write() < 0)
                return -1;

            if (para_list != null && para_list.Count > 0)
            {
                for (int i = 0; i < para_list.Count; i++)
                {
                    sql = sql.Replace(para_list[i].ParameterName, para_list[i].Value.ToString());
                }
            }
            format_logstr(sql, LogLevel.INFO);
            return write_log();
        }

        public static int WriteLog(string logstr)
        {
            if (before_write() < 0)
                return -1;
            format_logstr(logstr, LogLevel.INFO);
            return write_log();
        }

        public static int WriteLogWarn(string logstr)
        {
            if (before_write() < 0)
                return -1;
            format_logstr(logstr, LogLevel.WARN);
            return write_log();
        }

        public static int WriteLogError(string logstr)
        {
            if (before_write() < 0)
                return -1;
            format_logstr(logstr, LogLevel.ERROR);
            return write_log();
        }

        private static int before_write()
        {
            if (!File.Exists(m_path))
            {
                try
                {
                    FileStream fs = File.Create(m_path);
                    fs.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return -1;
                }
            }

            FileInfo info = new FileInfo(m_path);
            if (info.Length > 1024 * 1024 * 10)
            {
                try
                {
                    string path = m_path + DateTime.Now.Year + "_" + DateTime.Now.Month + "_" + DateTime.Now.Day + "_" + DateTime.Now.Hour + "_" + DateTime.Now.Minute + "_" + DateTime.Now.Second;
                    info.MoveTo(path);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return -1;
                }
            }
            return 0;
        }

        private static void format_logstr(string logstr, LogLevel level)
        {
            StackFrame sf = new StackFrame(2, true);
            string full_name = sf.GetFileName();
            string name = full_name.Substring(full_name.LastIndexOf("\\") + 1);
            switch (level)
            {
                case LogLevel.INFO:
                    m_logstr = "[" + DateTime.Now.ToString() + "][" + name + "][" + sf.GetMethod().Name + "][" + sf.GetFileLineNumber() + "][INFO]" + logstr + "\r\n";
                    break;
                case LogLevel.WARN:
                    m_logstr = "[" + DateTime.Now.ToString() + "][" + name + "][" + sf.GetMethod().Name + "][" + sf.GetFileLineNumber() + "][WARN]" + logstr + "\r\n";
                    break;
                case LogLevel.ERROR:
                    m_logstr = "[" + DateTime.Now.ToString() + "][" + name + "][" + sf.GetMethod().Name + "][" + sf.GetFileLineNumber() + "][ERROR]" + logstr + "\r\n";
                    break;
                default:
                    break;
            }
        }

        private static int write_log()
        {
            FileStream fs = null;
            try
            {
                byte[] bytes = Encoding.Default.GetBytes(m_logstr);
                fs = new FileStream(m_path, FileMode.Append, FileAccess.Write);
                fs.Write(bytes, 0, bytes.Length);
                fs.Flush();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return -1;
            }
            finally
            {
                fs.Close();
            }
            return 0;
        }

        private static string m_path = "";
        private static string m_logstr = "";
    }
}
